<?php declare(strict_types=1);

namespace Zyucv7\Core\Router;

// 路由处理类
class Route
{
    private string $method; // 方法
    private string $pattern; // 路由模式
    private $handler; // 路由模式
    private array $params = [];

    public function __construct(string $method, string $route, $handler)
    {
        $this->method = $method;
        $this->handler = $handler;

        // Convert route to regex pattern with named captures for params
        $pattern = preg_replace('/\/:(\w+)/', '/(?P<$1>[^/]+)', $route);
        $pattern = '#^' . $pattern . '$#';
        $this->pattern = $pattern;
    }

    public function match($method, $path)
    {
        if ($this->method !== $method) {
            return false;
        }

        if (preg_match($this->pattern, $path, $matches)) {
            // Extract params from named captures
            foreach ($matches as $key => $value) {
                if (is_string($key)) {
                    $this->params[$key] = $value;
                }
            }
            return true;
        }
        return false;
    }

    public function getHandler()
    {
        return $this->handler;
    }

    public function getParams()
    {
        return $this->params;
    }
}
